// Knowledge Graph Service - 知识图谱服务

use axum::{
    extract::{Json, Query, State},
    http::StatusCode,
    routing::{get, post},
    Router,
};
use common::ApiResponse;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use auth::AuthUser;

// ========== 数据模型 ==========

#[derive(Debug, Serialize, Deserialize)]
struct KnowledgePoint {
    id: String,
    name: String,
    subject: String,
    level: i32,  // 层级：1=学科, 2=章节, 3=知识点, 4=子知识点
    parent_id: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
struct LearningPath {
    knowledge_points: Vec<KnowledgePoint>,
    total_points: usize,
    estimated_hours: f64,
}

// ========== API 请求/响应 ==========

#[derive(Debug, Deserialize)]
struct CreateKnowledgePointRequest {
    name: String,
    subject: String,
    level: i32,
    parent_id: Option<String>,
}

#[derive(Debug, Deserialize)]
struct PathQuery {
    student_id: String,
    subject: Option<String>,
}

// ========== 应用状态 ==========

#[derive(Clone)]
struct AppState {
    neo4j_uri: String,
    neo4j_user: String,
    neo4j_password: String,
}

// ========== 处理器 ==========

/// 健康检查
async fn health_check() -> (StatusCode, Json<ApiResponse<String>>) {
    (StatusCode::OK, Json(ApiResponse::ok("OK".to_string())))
}

/// 创建知识点
async fn create_knowledge_point(
    _auth_user: AuthUser,
    State(_state): State<Arc<AppState>>,
    Json(req): Json<CreateKnowledgePointRequest>,
) -> (StatusCode, Json<ApiResponse<KnowledgePoint>>) {
    let kp = KnowledgePoint {
        id: common::generate_id(),
        name: req.name,
        subject: req.subject,
        level: req.level,
        parent_id: req.parent_id,
    };

    tracing::info!("Knowledge point created: {}", kp.id);
    (StatusCode::CREATED, Json(ApiResponse::ok(kp)))
}

/// 获取学习路径
async fn get_learning_path(
    _auth_user: AuthUser,
    State(_state): State<Arc<AppState>>,
    Query(query): Query<PathQuery>,
) -> (StatusCode, Json<ApiResponse<LearningPath>>) {
    let path = LearningPath {
        knowledge_points: vec![KnowledgePoint {
            id: "kp1".to_string(),
            name: "函数基础".to_string(),
            subject: "数学".to_string(),
            level: 3,
            parent_id: Some("chapter1".to_string()),
        }],
        total_points: 1,
        estimated_hours: 2.0,
    };

    tracing::info!("Generated learning path for student: {}", query.student_id);
    (StatusCode::OK, Json(ApiResponse::ok(path)))
}

// ========== 主函数 ==========

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    use common::service::*;
    
    init_tracing();
    dotenvy::dotenv().ok();

    let state = Arc::new(AppState {
        neo4j_uri: env_or("NEO4J_URI", "bolt://localhost:7687"),
        neo4j_user: env_or("NEO4J_USER", "neo4j"),
        neo4j_password: env_or("NEO4J_PASSWORD", "password"),
    });

    let app = Router::new()
        .route("/health", get(health_check))
        .route("/api/v1/knowledge/points", post(create_knowledge_point))
        .route("/api/v1/knowledge/learning-path", get(get_learning_path))
        .with_state(state);

    start_service("Knowledge graph service", &env_or("KNOWLEDGE_SERVICE_PORT", "8085"), app).await
}

